import 'package:cbec_app/components/base/base_ctr.dart';
import 'package:cbec_app/components/common/common_style.dart';
import 'package:cbec_app/components/http/network.dart';
import 'package:cbec_app/pages/my/controller/my_ctr.dart';
import 'package:cbec_app/routes/routes.dart';
import 'package:cbec_app/utils/AppData.dart';
import 'package:cbec_app/utils/EventMgr.dart';
import 'package:cbec_app/utils/ThemeConfig.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:cbec_app/utils/logger.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:fluwx/fluwx.dart';
import 'package:get/get.dart';
import 'package:umeng_common_sdk/umeng_common_sdk.dart';
import 'dart:async';

import '../../../components/app_conifg.dart';
import '../../../utils/GlobalData.dart';
import '../../../utils/prevent_double_tap.dart';
import '../../bags/controller/bags_ctr.dart';
import '../../home/controller/home_ctr.dart';

///登录页控制器
class LoginController extends BaseController {
  var phoneNumber = ''; //手机号
  var encryptPhone = ''; //加密手机号
  var btnTxt = "本机器号码一键登录";
  var buttonColor = ThemeConfig.themeColor; //Tools.fromHex("#F58E84").obs;//不可点击的样式
  var hidePassword = true;
  var passWordHideShowPic = 'hide_password.png';

  //密码
  var password = '';
  //确认密码
  var confirmPassword = '';

  ///是否同意用户协议
  var isAgree = false;

  ///登录类型 1、本地号码登录（如果登录过的话） 2、手机号登录 3、账号密码登录、4、 注册
  var status = 1;

  var countryTxt = "中国(+86)";

  var countdown = 0;
  var countdownTxt = '重新发送';

  ///验证码类型
  String smsType = 'phoneLogin';

  ///重设密码验证码
  String resetCode = '';

  ///重试密码手机号控制器
  TextEditingController phoneCtr = TextEditingController();

  Timer? timer;

  ///支付插件
  Fluwx fluwx = Fluwx();
  late Function(WeChatResponse) responseListener;

  bool isWeChatAuthTag = false;

  @override
  void onInit() {
    super.onInit();
    if (GetPlatform.isAndroid || GetPlatform.isIOS) {
      ///微信登录监听
      responseListener = (response) {
        print('微信登录监听 ======');
        if (response is WeChatAuthResponse) {
          if (PreventDoubleTap().onDoubleTap()) {
            print('isWeChatAuthTag == ${isWeChatAuthTag}');
            if (response.errCode == 0 && isWeChatAuthTag == false) {
              print('微信授权 ${response.toRecord()}');
              isWeChatAuthTag = true;
              wechatLogin(response.code!);
            } else if (response.errCode == -4) {
              Tools.showToast('用户拒绝授权');
            }
          }
        }
      };

      fluwx.addSubscriber(responseListener);
    }

    //判断是否登录过
    status = 2;
    // if (AppData.isLogin) {
    //   //未登录过
    //   status = 2;
    // }
    // else {
    //   //已登录过
    //   status = 1;
    //   //加密获取到的手机号
    //   phoneNumber = AppData.phoneNumber!;
    //   encryptPhone = Tools.encryptPhoneNumber(AppData.phoneNumber!);
    // }
    checkStatus(status);

    update();

    ///验证码倒计时
    startCountdown();
  }

  ///微信登录
  void wechatLogin(String code) {
    Tools.showLoading();
    print('wechatLogin ===== 1');
    Network.wechatAuthLogin(code).then((value) {
      print('wechatLogin ===== 2');
      Tools.hideLoading();
      if (value['isExistsOpenId']) {
        //已绑定
        AppData.tokenName = value['tokenName'];
        AppData.tokenValue = value['tokenValue'];

        loginSuccess();
      } else {
        //未绑定，跳转绑定页
        Tools.showToast('请完成账号绑定');
        Get.toNamed('${Routes.phoneBindWechat}/?openId=${value['openId']}');
      }
    }).catchError((onError) {
      Tools.hideLoading();
    });
  }

  //密码显隐
  void showHidePassword() {
    hidePassword = !hidePassword;
    if (hidePassword == true) {
      //显示眼睛闭着
      passWordHideShowPic = 'hide_password.png';
    } else {
      //显示眼睛睁开
      passWordHideShowPic = 'show_password.png';
    }
    update();
  }

  ///选择国家
  void changeCountry(String text) {
    countryTxt = text;
    update();
  }

  ///修改当前状态
  void checkStatus(int mstatus) {
    status = mstatus;
    switch (status) {
      case 1:

        ///一键登录
        btnTxt = "本机器号码一键登录";
      case 2:
        //验证码登录
        smsType = 'phoneLogin';
        btnTxt = "获取验证码";
        break;
      case 3:
        //账号密码登录
        btnTxt = "登录";
        break;
      case 4:
        //注册
        smsType = 'regist';
        btnTxt = "下一步";

        break;
      case 5:
        //忘记密码
        smsType = 'resetpwd';
        phoneCtr.value = phoneCtr.value.copyWith(text: phoneNumber);
      default:
        btnTxt = "ss";
    }
    // print(status);
    update();
  }

  //提交
  void submit() {
    switch (status) {
      case 1:
        break;
      case 2: //手机号登录
        //登录验证码登录
        {
          getLoginCode();
        }
        break;
      case 3:
        //账号密码登录
        {
          accountLogin();
        }
        break;
      case 4: //注册
        {
          getRegisterCode();
        }
        break;
      default:
    }
    update();
  }

  ///监听手机号输入
  void onInputPhone(String value) {
    phoneNumber = value;
  }

  ///监听密码输入
  void onInputPassword(String value) {
    password = value;
  }

  ///监听确认密码输入
  void onInputConfirmPassword(String value) {
    confirmPassword = value;
  }

  ///监听重设密码验证码输入
  void onInputResetCode(String value) {
    resetCode = value;
  }

  ///获取重试密码验证码
  void getResetCode() {
    if (!Tools.checkEmpty(phoneNumber)) {
      Tools.showToast('请输入手机号');
      return;
    }
    if (countdown > 0) {
      Tools.showToast('$countdown秒后可重新获取');
      return;
    }
    Tools.showLoading();
    Network.getMsgCode(phoneNumber, smsType).then((value) {
      Tools.hideLoading();
      if (value) {
        Tools.showToast('验证码已发送');
        countdown = 60;
      }
    }).catchError((onError) {
      Tools.hideLoading();
    });
  }

  ///完成重设密码
  void completeResetPassword() {
    Map<String, dynamic> params = {};
    params['code'] = resetCode;
    params['mobile'] = phoneNumber;
    params['newPassword'] = password;
    params['confirmPassword'] = confirmPassword;
    params['sid'] = AppData.sid;
    params['smsType'] = smsType;
    if (!Tools.checkEmpty(password)) {
      Tools.showToast('请输入新密码');
      return;
    }
    if (!Tools.checkEmpty(confirmPassword)) {
      Tools.showToast('请输入确认密码');
      return;
    }
    if (!Tools.checkEqual(password, confirmPassword)) {
      Tools.showToast('两次密码不一致');
      return;
    }
    if (!Tools.checkEmpty(resetCode)) {
      Tools.showToast('请输入短信验证码');
      return;
    }
    Tools.showLoading(title: '请稍候...');
    Network.forgetPassword(params).then((value) {
      Tools.hideLoading();
      Tools.showToast('密码重置成功');
    }).catchError((onError) {
      Tools.hideLoading();
    });
  }

  ////校验是否同意用户协议
  bool checkAgree() {
    if (isAgree) {
      return true;
    } else {
      Tools.showModal(
        cancelText: '不同意',
        confirmText: '同意',
        isRichText: true,
        richText: Text.rich(TextSpan(children: [
          TextSpan(text: '请阅读并同意'),
          TextSpan(text: '《用户协议》', style: setTextStyle(15, FontWeight.w500, ThemeConfig.tagColor)),
          TextSpan(text: '《隐私协议》', style: setTextStyle(15, FontWeight.w500, ThemeConfig.tagColor)),
        ])),
        onConfirm: (tag) {
          isAgree = true;
          update();
          SmartDialog.dismiss(tag: tag);
        },
      );
      return false;
    }
  }

  ///通用校验
  bool commonCheck() {
    if (!Tools.checkEmpty(phoneNumber)) {
      Tools.showToast('请输入手机号');
      return false;
    }

    if (!Tools.isValidMobile(phoneNumber)) {
      Tools.showToast('手机号格式不正确');
      return false;
    }

    if (!checkAgree()) {
      return false;
    }

    return true;
  }

  ///获取登录验证码
  void getLoginCode() {
    if (!commonCheck()) {
      return;
    }
    Tools.showLoading(title: '请稍候');
    Network.getMsgCode(phoneNumber, smsType).then((value) {
      Tools.hideLoading();
      if (value) {
        Tools.showToast('验证码已发送');
        Get.toNamed(Routes.verityCode);
        countdown = 60;
      }
    }).catchError((onError) {
      Tools.hideLoading();
    });
  }

  ///账号密码登录
  void accountLogin() {
    if (!commonCheck()) {
      return;
    }

    if (!Tools.checkEmpty(phoneNumber)) {
      Tools.showToast('请输入手机号');
      return;
    }
    if (!Tools.checkEmpty(password)) {
      Tools.showToast('请输入密码');
      return;
    }
    if (!checkAgree()) {
      return;
    }

    Tools.showLoading(title: '登录中...');
    Network.accountLogin(phoneNumber, password).then((value) {
      Tools.hideLoading();
      AppData.phoneNumber = phoneNumber;
      loginSuccess();
    }).catchError((onError) {
      Tools.hideLoading();
    });
  }

  ///登录成功
  void loginSuccess() {
    UmengCommonSdk.onProfileSignIn(AppData.tokenName!);
    AppData.isLogin = true;
    final myController = Get.find<MyController>();
    myController.onPageRefresh();

    final bagsController = Get.find<BagsController>();
    bagsController.onPageRefresh();
    bagsController.update();

    final homeController = Get.find<HomeController>();
    homeController.isLogin = true;
    homeController.update();

    print('登录成功走了没');
    Get.until((route) => Get.currentRoute == Routes.main);
    Tools.showToast('登录成功');
  }

  ///获取注册验证码
  void getRegisterCode() {
    if (!commonCheck()) {
      return;
    }
    Tools.showLoading();
    Network.getMsgCode(phoneNumber, smsType).then((value) {
      Tools.hideLoading();
      if (value) {
        Tools.showToast('验证码已发送');
        Get.toNamed(Routes.verityCode);
        countdown = 60;
      }
    }).catchError((onError) {
      Tools.hideLoading();
    });
  }

  ///重新获取验证码
  void reGetCode() {
    if (countdown > 0) {
      Tools.showToast('$countdown秒后可重新获取');
      return;
    }
    Tools.showLoading();
    Network.getMsgCode(phoneNumber, smsType).then((value) {
      Tools.hideLoading();
      if (value) {
        Tools.showToast('验证码已发送');
        countdown = 60;
      }
    }).catchError((onError) {
      Tools.hideLoading();
    });
  }

  void startCountdown() {
    //---这里请求发送验证码的接口---
    timer = Timer.periodic(Duration(seconds: 1), (timer) {
      if (countdown >= 1) {
        countdown--;
        countdownTxt = "重新发送(${countdown.toString()}s)";
      } else {
        countdownTxt = status == 5 ? '获取验证码' : '重新发送';
        // timer.cancel();
      }
      update();
    });
  }

  ///接收用户发送的验证码
  void submitVerify(String code) {
    switch (status) {
      case 2:
        //登录,这里调用登录接口把验证码和手机号提交给后台
        Tools.showLoading(title: '登录中...');
        Network.phoneLogin(phoneNumber, code, smsType).then((value) {
          Tools.hideLoading();
          AppData.phoneNumber = phoneNumber;
          AppData.tokenName = value['tokenName'];
          AppData.tokenValue = value['tokenValue'];
          AppData.cid = value['cid'];
          AppData.sid = value['sid'];
          GlobalData.sid = value['sid'];
          loginSuccess();
        }).catchError((onError) {
          print('错误原因 =====$onError');
          Tools.hideLoading();
        });
        //------------------------------
        //登录成功的话跳转到首页并删除前面的所有路由
        break;
      case 4:
        //注册,跳转到注册的二级页面输入账号和密码
        Network.checkMsgCode(phoneNumber, code, smsType).then((value) {
          if (value) {
            Get.toNamed(Routes.resigter);
          }
        });
        break;
      default:
      //其他类型,不做操作
    }
  }

  ///完成注册
  void completeRegister() {
    //表单校验
    Map<String, dynamic> params = {};
    params['confirmPassword'] = password;
    params['newPassword'] = confirmPassword;
    params['mobile'] = phoneNumber;
    params['sid'] = AppData.sid;
    params['cid'] = 1;
    params['client'] = GetPlatform.isIOS ? AppConfig.clientIos : AppConfig.clientAndroid;
    params['registrationId'] = AppData.jPushRegistrationID;
    params['lastLoginPlatform'] = GetPlatform.isIOS ? 2 : 1;
    logger.d('表单 $params');
    if (!Tools.checkEmpty(password)) {
      Tools.showToast('请输入密码');
      return;
    }
    if (!Tools.checkEmpty(confirmPassword)) {
      Tools.showToast('请输入确认密码');
      return;
    }
    if (!Tools.checkEqual(password, confirmPassword)) {
      Tools.showToast('两次密码不一致');
      return;
    }
    Tools.showLoading(title: '注册中...');
    Network.completeRegister(params).then((value) {
      Tools.hideLoading();
      AppData.phoneNumber = phoneNumber;
      AppData.tokenName = value['tokenName'];
      AppData.tokenValue = value['tokenValue'];
      AppData.cid = value['cid'];
      AppData.sid = value['sid'];
      GlobalData.sid = value['sid'];
      loginSuccess();
    }).catchError((onError) {
      Tools.hideLoading();
    });
  }

  ///微信授权登录
  void wechatAuth() async {
    if (!checkAgree()) {
      return;
    }

    bool isInstall = await fluwx.isWeChatInstalled;
    if (!isInstall) {
      Tools.showToast('请先安装微信');
      return;
    }

    fluwx.authBy(which: NormalAuth(scope: 'snsapi_userinfo', state: 'wechat_sdk_demo_test')).then((value) {});
  }

  @override
  void onClose() {
    super.onClose();
    if (timer != null) {
      timer!.cancel();
    }
  }
}
